<?php

namespace app\api\controller;

use alipay\aop\AopClient;
use app\common\controller\Api;
use app\common\library\Pay;
use app\common\model\campsite\Order as CampsiteOrder;
use app\common\model\fittings\Order as FittingsOrder;
use app\common\model\lease\Order as LeaseOrder;
use app\common\model\modify\Order as ModifyOrder;
use app\common\model\MoneyLog;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\Order;
use app\common\model\product\Member as ProductMember;
use app\common\model\Requirement;
use app\common\model\requirement\Lists;
use app\common\model\ScoreLog;
use app\common\model\User;
use app\common\model\user\Level;
use app\common\model\user\LevelLog;
use app\common\model\user\Log as UserLog;
use think\Db;
use think\Log;

/**
 * 回调接口
 */
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 回调
     */
    public function alipayNotify()
    {
        $post = $_POST;
        if (empty($post)) { //判断POST来的数组是否为空
            return false;
        }
        Log::write('记录日志：' . json_encode($post), 'err');
        $post['fund_bill_list'] = htmlspecialchars_decode($post['fund_bill_list']);
        $aop = new AopClient();
        $alipayrsaPublicKey = config('site.alipay_public_key');
        $check = $aop->rsaCheckV1($post, $alipayrsaPublicKey, "RSA2");
        Log::write('验证结果:' . json_encode($check));
        extract($post);
        if ($check) {
            //商户订单号
            //支付宝交易号
            if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {
                $str = substr($out_trade_no, 0, 2);
                if ($str == 'NO') {
                    Pay::orderFulfillment($out_trade_no,  $trade_no);
                }
                echo "success";
            } else {
                Log::error('trade_status不存在:');
            }
        } else {
            //验证失败
            echo "fail";   //请不要修改或删除
        }
    }

    /**
     * 微信回调
     */
    public function wechatNotify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        // $data='{"id":"7f769483-ba0f-5e34-bc3b-299637f52e70","create_time":"2023-07-19T18:17:51+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"M51+nO17THBak9hnDcmBB2wCRgSMfFDQTDPpHzkVHs0Y9g2MZmb7dH6I2iPs9nT3TO2MdGaRi1/pbhcDqr6ip6TQXIzCtHA9IDsznh6kcnx+FKyCkZmepTaioamfo3vNYxTDWb+IW8EFzE6MkL1nA8pPv0Cu35/VCJ3E8a4yd6TOlAKda7mndHXNTd5v4DQNVsAMZ7GMHIcC1GlFmKlTFFtLAnkp5JBtbsOgh6EFX/Ila8DcSnseCFBMVQvJ7cT00uUbWzp0pcTz2vl2LgQYkJaO5js2iITI9E/PKJBm+WO0YG4qzDgaCwbOhi0DaRtt8uIRyhe7zV2ygM5KHc7js5FToV3sO52QTTBVidAaNG1I27G1LNk/se3+VDfvkhZCM29s2hUrRsbxIbFp6IrbWwcmndL9iRjsCpWrRBHB19sjhkpi0l0v1Fw6rzeBMnqhbZ6iHK1fxX2kHMkzKZcre0/nlNpz65WYJnKDgL+81v5aAXAfUgS5rqXrDm6WrCrlOz04cpnhqZwIsinxwjy/UzOeby56LK2fXFMqMP7UDVGQh6BRPdU/Ht8b+I1xFiKt0wOVwi0gXCc=","associated_data":"transaction","nonce":"8fBfKfrycCL2"}}';
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'QbyyrkXYWbwSVT3kw3FwBj1xv9b8rLLu');
            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            // Db::name('pay_log')->insert(['data' => $orderData]);
            $orderData = json_decode($orderData, true);
            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                $time = time();
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'modify':
                            $order = ModifyOrder::get(['sn' => $order_sn, 'status' => '0']);
                            $order->status = '1';
                            $order->paytime = $time;
                            $order->transaction_id = $transaction_id;
                            $order->save();
                            break;
                        case 'campsite':
                            $order = CampsiteOrder::get(['sn' => $order_sn, 'status' => '0']);
                            $order->status = '1';
                            $order->paytime = $time;
                            $order->transaction_id = $transaction_id;
                            $order->save();
                            break;
                        case 'lease':
                            $order = LeaseOrder::get(['sn' => $order_sn, 'status' => '0']);
                            $order->status = '1';
                            $order->paytime = $time;
                            $order->transaction_id = $transaction_id;
                            $order->save();
                            break;
                        case 'fittings':
                            $order = FittingsOrder::get(['sn' => $order_sn, 'status' => '0']);
                            $order->status = '1';
                            $order->paytime = $time;
                            $order->transaction_id = $transaction_id;
                            $order->save();
                            break;
                    }
                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return 'SUCCESS';
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }

    //退款回调地址
    public static function refundNotify()
    {
        $notifiedData = file_get_contents('php://input');
        $data = json_decode($notifiedData, true);
        Log::write('验证退款：' . $data);

        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'QbyyrkXYWbwSVT3kw3FwBj1xv9b8rLLu');
            $orderData = json_decode($orderData, true);
            Log::write('退款成功：' . $orderData);

            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                $order = FittingsOrder::get(['transaction_id' => $transaction_id]);
                if ($order->settlement == 0) {
                    return json(['code' => 'SUCCESS', 'message' => '成功']);
                }
                $user = User::get($order->user_id);
                if ($order->p_id) {
                    $puser = User::get($order->p_id);
                    if ($puser->total_interests <= $order->p_interests) {
                        $puser->total_interests = 0;
                    } else {
                        $puser->setDec('total_interests', $order->p_interests);
                    }
                }
                //分红金额扣除
                if ($order->dividend > 0) {
                    //扣除可分红金额
                    if ($user->use_dividend <= $order->dividend) {
                        $user->use_dividend = 0;
                    } else {
                        $user->setDec('use_dividend', $order->dividend);
                    }
                    //扣除合计分红金额
                    if ($user->total_dividend <= $order->dividend) {
                        $user->total_dividend = 0;
                    } else {
                        $user->setDec('total_dividend', $order->dividend);
                    }
                }
                //权益值扣除
                if ($order->interests > 0) {
                    if ($user->total_interests <= $order->interests) {
                        $user->setDec('total_interests', $order->total_interests);
                    } else {
                        $user->setDec('total_interests', $order->interests);
                    }
                }
                //累计消费扣除
                if ($order->pay_money > 0) {
                    $user->setDec('consumption', $order->pay_money);
                }

                //上级累计权益值扣除
                if ($order->p_id > 0) {
                    $puser = User::get($order->p_id);
                    if ($order->p_interests >= $puser->total_interests) {
                        $puser->setDec('total_interests', $order->total_interests);
                    } else {
                        $puser->setDec('total_interests', $order->p_interests);
                    }
                }


                // if ($order->interests > 0) {
                //     if ($order->interests >= $user->total_interests) {
                //         $order->refund_interests = $user->total_interests;
                //     }
                //     if ($order->interests < $user->total_interests) {
                //         $order->refund_interests = $order->interests;
                //     }
                //     $user->use_dividend = $order->refund_interests;

                // }
                $order->save();
                $user->save();
                // $res = Order::where('transaction_id',  $transaction_id)->update(['status' => 6, 'returntime' => time()]);


                /*业务处理*/
                return json(['code' => 'SUCCESS', 'message' => '成功']);
            }
        }
    }
}
